# -*- coding: utf-8 -*-

import datetime
import json

from script_utils import query, get_one2list, oid2nid, get_one2dict
from script_utils import models
from app.models.order import Payment, OrderItem, Order, ProductSKU
from bson.objectid import ObjectId
import time


def migrate_payment():
    cols = [
        "id",
        "plan_id",
        "price",
        "pay_type",
        "name",
        "orders",
        "thirdparty_payment_id",
        "status",
        "return_msg",
        '"user"',
        "device_id",
        "is_used_sale",
        "is_active",
        "date_added"

    ]
    print 'start migrate payment...'
    for row in query('vacation_payment', cols=cols):
        obj = dict(zip(cols, row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_payment"][oid]

        old_plan_id = obj['plan_id']
        if old_plan_id:
            obj['plan_id'] = oid2nid["vacation_userplan"][old_plan_id]
        obj["user"] = obj['"user"']
        del obj['"user"']

        # date_add 改成 created_time
        # created_time = obj['date_added']
        # obj['created_time'] = created_time
        # del obj['date_added']

        Payment(**obj).save()
    print 'finish migrate payment...'


def migrate_order():
    """
    一般 XX_ID 是外键，要替换成mongodb的新ID
    """
    cols = [
        "id",
        "product_id",
        "plan_id",
        "payment_id",
        "supplier_id",
        "first_name",
        "last_name",
        "contact_name_en",
        "contact_email",
        "contact_address",
        "contact_name",
        "contact_tel",
        "sex",
        "device_id",
        "status",
        "unique_id",
        "is_valid",
        "is_tipped",
        "is_active",
        "user_id",
        "source",
        "bt_order_id",
        "last_modified",
        "reason",
        "cancel_date",
        "is_updated",
        "date_added",
        "custom_option",
        "surcharge",
        "flight",
        "express",
        "booked_date",
        "date",
        "time",
        "hotel_type",
        "hotel_name",
        "second_hotel_name",
        "baby_count",
        "exceed_people_count",
        "waiting_date",
        "waiting_time",
        "supplier_order_id",
        "supplier_voucher",
        "plan_type",
        "start_date",
        "end_date",
        "credentials_category",
        "credentials_number",
        "birth_date",
        "proposalno",
        "policyno",
        "pay_date",
        "refund_account",
        "to_finance_date",
        "finance_price",
        "finance_pay",
        "currency",
        "image",
        "description",
    ]
    SEX_CHOICES = {0: 'male', 1: 'female', 2: 'secret'}
    print 'start migrate order ...'
    for row in query('vacation_productorder', cols=cols):
        old_obj = dict(zip(cols, row))
        old_obj['info'] = {}

        # 处理订单本身ID
        old_obj['id'] = oid2nid['vacation_productorder'][old_obj['id']]
        # print old_obj['id']

        # 处理产品外键
        old_product_id = old_obj['product_id']
        new_product_id = oid2nid['vacation_product'][old_product_id]
        old_obj['product'] = new_product_id
        del old_obj['product_id']

        # 处理用户计划原外键，目前设计中已移除
        old_plan_id = old_obj['plan_id']
        if old_plan_id:
            new_plan_id = oid2nid['vacation_productorder'][old_plan_id]
        else:
            new_plan_id = None
        old_obj['plan_id'] = new_plan_id
        # del old_obj['plan_id']

        # 处理支付外键
        old_payment_id = old_obj['payment_id']
        if old_payment_id:
            new_payment_id = oid2nid['vacation_payment'][old_payment_id]
        else:
            new_payment_id = None
        old_obj['payment'] = new_payment_id
        del old_obj['payment_id']


        # 处理供应商外键 存进orderitem_obj里, 并且新order模型不再关联
        old_supplier_id = old_obj['supplier_id']
        if old_supplier_id:
            new_supplier_id = oid2nid['vacation_supplier'][old_supplier_id]
        else:
            new_supplier_id = None
        old_obj['info']['supplier_id'] = new_supplier_id
        del old_obj['supplier_id']

        # 处理性别字段
        old_obj['sex'] = SEX_CHOICES[old_obj['sex']]

        # 处理保留在order字段 ，字段名有变更
        # old_obj['contact_first_name'] = old_obj['first_name']
        # old_obj['contact_last_name'] = old_obj['last_name']
        # old_obj['cancel_reason'] = old_obj['reason']
        # old_obj['created_time'] = old_obj['date_added']
        # old_obj['updated_time'] = old_obj['last_modified']
        # del old_obj['first_name']
        # del old_obj['last_name']
        # del old_obj['reason']
        # del old_obj['is_updated']
        # del old_obj['date_added']
        # del old_obj['last_modified']

        # 处理 时间格式 : date --> datetime
        date_field = ['date', 'waiting_date', 'start_date', 'end_date',
                      'birth_date']
        for field in date_field:
            value = old_obj[field]
            if value:
                old_obj[field] = datetime.datetime(value.year, value.month,
                                                   value.day)
        # 处理 时间格式 : time --> datetime
        time_field = ['waiting_time', 'time']  # time是接机时间
        for filed_name in time_field:
            wt = old_obj[filed_name]
            if isinstance(wt, datetime.time):
                old_obj[filed_name] = wt.strftime("%H:%M:%S")

        # 处理自定义字段
        if old_obj['custom_option']:
            custom_option = json.loads(old_obj['custom_option'])
            old_obj['custom_option'] = {}
            for i in custom_option:
                old_obj['custom_option'].update(i)

        # 从order中移除的字段，并且保存到info
        info_filed = ["surcharge", "flight", "express",
                      "booked_date", "date", "time", "hotel_type", "hotel_name",
                      "second_hotel_name", "baby_count", "exceed_people_count",
                      "waiting_date", "waiting_time",
                      "supplier_order_id", "supplier_voucher", "plan_type",
                      "start_date", "end_date", "credentials_category",
                      "credentials_number", "birth_date", "proposalno",
                      "policyno"]

        for filed_name in info_filed:
            value = old_obj[filed_name]
            # if filed_name == 'express':
            #     new_filed_name = 'express_no'
            # elif filed_name == 'date':
            #     new_filed_name = 'use_date'
            # elif filed_name == 'time':
            #     new_filed_name = 'pick_up_time'
            #
            # else:
            #     new_filed_name = filed_name
            old_obj['info'][filed_name] = value
            del old_obj[filed_name]

        # 处理财务字段， 放在order.finance (EmbeddedField)
        finance_field = ["pay_date", "refund_account", "to_finance_date",
                         "finance_price", "finance_pay", "currency", "image",
                         "description"]

        old_obj['finance'] = {}
        for filed_name in finance_field:
            old_obj['finance'][filed_name] = old_obj[filed_name]
            del old_obj[filed_name]

        # 处理用户外键 : 检索条件是user_id ，同样保存为user_id, 不用额外处理了
        order = Order(**old_obj)
        order.save()

    print 'Order Migration Job Done ~ '


def migrate_order_detail():
    """
    原model：OrderDetail
    新设计：将详情信息保存到 order.detail

    """
    cols = [
        "id",
        "order_id",
        "weixin",
        "get_on_address",
        "delivery_location",
        "shipping_address",
        "ticket_counter",
        "hotel_address",
        "reservation_number",
        "waiting_address",
        "bar_code",
        "take_off_time",
        "arrive_time",
        "admission_time",
        "user_waiting_time",
        "is_active",
        "date_added",
    ]
    print 'start migrate orderdetail...'
    for row in query('vacation_orderdetail', cols=cols):
        old_obj = dict(zip(cols, row))

        new_id = oid2nid['vacation_productorder'][old_obj['order_id']]
        order = Order.objects.filter(id=new_id).first()

        # print new_id, old_obj['order_id']
        # print order

        order['detail'] = {}
        for k, v in old_obj.items():
            # if k == 'date_added':
            #     k = 'created_time'
            if isinstance(v, datetime.time):
                v = v.strftime("%H:%M:%S")
            if isinstance(v, datetime.date):
                v = datetime.datetime(v.year, v.month, v.day)
            order['detail'][k] = v

        # print order['detail']
        # break
        order.save()
    print 'OrderDetail Migration Job Done ~'


def migrate_order_recognizee():
    """
    原model: OrderRecognizee
    改动：
        sex: 原保存0，1, 2，现改成存 male, female, secret

    新设计：将所有信息保存到 order['info_recognizee']
    """
    cols = [
        "id",
        "order_id",
        "relation",
        "name",
        "sex",
        "credentials_category",
        "credentials_number",
        "birth_date",
        "tel",
        "email",
        "is_active",
        "date_added",
    ]
    SEX_CHOICES = {0: 'male', 1: 'female', 2: 'secret'}
    print 'start migrate order recognizee...'
    for row in query('vacation_orderrecognizee', cols=cols):
        old_obj = dict(zip(cols, row))
        old_order_id = old_obj['order_id']
        new_order_id = oid2nid['vacation_productorder'][old_order_id]
        order = Order.objects.get(id=new_order_id)
        order['info_recognizee'] = {}

        for k, v in old_obj.items():
            # if k == 'date_added':
            #     k = 'created_time'
            if k == 'sex':
                v = SEX_CHOICES[old_obj['sex']]
            if isinstance(v, datetime.date):
                v = datetime.datetime(v.year, v.month, v.day)
            order['info_recognizee'][k] = v
        # print order['info_recognizee']
        # TODO Save
        order.save()
    print 'OrderRecognizee Migration Job Done ~'


def migrate_order_product_type():
    """
    原model: OrderProductType
    改动：

    新设计：将所有信息保存到 order.items
    type: ProductType(康师傅改成了ProductSKU)
    order: 移除关联
    time : 干掉了（ProductTime模型也干掉）
    count -> quantity

    其他字段，应该放在其他地方，迁移时，暂时放在 --> item.info, DictField

    """
    cols = [
        "id",
        "type_id",
        "order_id",
        # "time_id",
        "name",
        "name_en",
        "description",
        "fee",
        "count",
        "category",
        "use_days",
    ]

    print 'start migrate OrderProductType..'

    # 重复运行时，清除错误或者不在需要的数据
    count = Order.objects.all().update(items=[])
    print count
    # print orders.count()
    # orders.update(items=[])
    OrderItem.objects.delete()
    # time.sleep(10)

    for row in query('vacation_orderproducttype', cols=cols):
        old_obj = dict(zip(cols, row))
        old_order_id = old_obj['order_id']
        new_order_id = oid2nid['vacation_productorder'][old_order_id]

        item = OrderItem()

        order = Order.objects.get(id=new_order_id)
        item.order = order
        # item.info['order_id'] = old_obj['order_id']
        del old_obj['order_id']

        # 关联所属产品
        item.product = order.product

        # type -> product_sku
        old_type_id = old_obj['type_id']
        new_type_id = oid2nid['vacation_producttype'][old_type_id]
        product_sku = ProductSKU.objects.get(id=new_type_id)
        item.product_sku = product_sku
        del old_obj['type_id']

        # count
        item.count = old_obj['count']
        del old_obj['count']

        # use_days
        item.price_factor['use_days'] = old_obj['use_days']
        del old_obj['use_days']

        # fee
        item.fee = old_obj['fee']
        del old_obj['fee']

        # 其他信息保存在 info字段（DictField）
        for k, v in old_obj.items():
            item.info[k] = v

        item.order = order
        item.save()
        order.items.append(item)
        order.save()

    print 'OrderProductType Migration Job Done ~'


if __name__ == '__main__':
    # 按顺序执行
    # migrate_payment()
    # migrate_order()
    # migrate_order_detail()
    # migrate_order_recognizee()
    # migrate_order_product_type()
    print u'All Migration Done'
